package main

import (
	"fmt"
	"log"

	"ddl_checker/pkg/analyzer"
)

func main() {
	fmt.Println("=== SQL分析器使用示例 ===")

	// 创建分析器实例
	analyzer := analyzer.DefaultAnalyzer()

	// 示例1: 解析多条SQL语句
	fmt.Println("\n1. 解析多条SQL语句:")
	batchSQL := `CREATE TABLE users (
		id INT PRIMARY KEY,
		name VARCHAR(100) NOT NULL
	);

	INSERT INTO users (id, name) VALUES (1, '张三');

	SELECT * FROM users WHERE id = 1;`

	statements, err := analyzer.ParseBatch(batchSQL, ";")
	if err != nil {
		log.Fatalf("解析失败: %v", err)
	}

	fmt.Printf("成功解析 %d 条SQL语句:\n", len(statements))
	for i, stmt := range statements {
		fmt.Printf("语句 %d:\n", i+1)
		fmt.Printf("  原始SQL: %s\n", stmt.OriginalSQL)
		fmt.Printf("  语法正确: %v\n", stmt.IsValid)
		fmt.Printf("  语句类型: %s\n", stmt.StatementType)
		fmt.Printf("  关联表: %v\n", stmt.Tables)
		fmt.Printf("  关联列: %v\n", stmt.Columns)
		fmt.Printf("  操作: %v\n", stmt.Operations)
		if stmt.Error != "" {
			fmt.Printf("  错误: %s\n", stmt.Error)
		}
		fmt.Println()
	}

	// 示例2: 验证SQL语法
	fmt.Println("2. 验证SQL语法:")
	testSQLs := []string{
		"SELECT * FROM users",
		"INVALID SQL SYNTAX",
		"CREATE TABLE test (id INT PRIMARY KEY)",
	}

	for _, sql := range testSQLs {
		isValid, errorMsg := analyzer.ValidateSQL(sql)
		fmt.Printf("SQL: %s\n", sql)
		fmt.Printf("  语法正确: %v\n", isValid)
		if !isValid {
			fmt.Printf("  错误信息: %s\n", errorMsg)
		}
		fmt.Println()
	}

	// 示例3: 分割SQL语句
	fmt.Println("3. 分割SQL语句:")
	splitSQL := "SELECT * FROM users; INSERT INTO logs (message) VALUES ('test'); UPDATE users SET name = '李四' WHERE id = 1;"
	splitStatements, err := analyzer.SplitStatements(splitSQL, ";")
	if err != nil {
		log.Fatalf("分割失败: %v", err)
	}

	fmt.Printf("分割为 %d 条语句:\n", len(splitStatements))
	for i, stmt := range splitStatements {
		fmt.Printf("%d. %s\n", i+1, stmt)
	}

	// 示例4: 获取分析结果
	fmt.Println("\n4. 获取分析结果:")
	resultStatements, err := analyzer.ParseBatch(batchSQL, ";")
	if err != nil {
		log.Fatalf("获取分析结果失败: %v", err)
	}

	validCount := 0
	invalidCount := 0
	var errors []string

	for _, stmt := range resultStatements {
		if stmt.IsValid {
			validCount++
		} else {
			invalidCount++
			if stmt.Error != "" {
				errors = append(errors, stmt.Error)
			}
		}
	}

	fmt.Printf("总语句数: %d\n", len(resultStatements))
	fmt.Printf("有效语句数: %d\n", validCount)
	fmt.Printf("无效语句数: %d\n", invalidCount)
	if len(errors) > 0 {
		fmt.Printf("错误信息: %v\n", errors)
	}
}
